//
//  PictureSelectorViewController.swift
//  sinaweibowj
//
//  Created by Macintosh on 15/12/25.
//  Copyright © 2015年 mactoinsh. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let margin:CGFloat = 5
private let rowCount :CGFloat = 3
private let imageCount  = 4

class PictureSelectorViewController: UICollectionViewController {
    
    var imageList = [UIImage]()
    
    init(){
        
        let layout = UICollectionViewFlowLayout()
        //计算每个cell的宽度
        let itemW = (screenW - (rowCount + 1) * margin) / rowCount
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        //设置组间距
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        super.init(collectionViewLayout: layout)
        //修改集合视图的背景颜色
        collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    
    
    
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let  delta = imageList.count == imageCount ? 0 : 1
        
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        
        //cell.backgroundColor = UIColor.randomColor()
        //设置图片选择器的代理
        cell.delegate = self
        //设置数据源
        if indexPath.item == imageList.count{
        cell.image = nil
        }else {
        cell.image = imageList[indexPath.item]
        }
        return cell
    }
    
}

extension PictureSelectorViewController:PictureSelectorCellDelegate{

    func userWillChoosePicture(cell:PictureSelectorCell) {
         print(__FUNCTION__)
        //如果点击的有图片image不为空，就直接返回
        if cell.image != nil {
        
        print("已经有 图片不要再点击了")
            return
        }
        
        //得到图片选择器
        let picker = UIImagePickerController()
        //设置允许编辑，上传用户头像的时候需要打开
        picker.allowsEditing = true
        //modla出对应的图片选择器
        presentViewController(picker, animated: true, completion: nil)
        //设置图片选择器的代理 一旦制定了代理对象，需要手动dismiss
        picker.delegate = self
        
    }

    func userWillDeletePicture(cell:PictureSelectorCell) {
        print(__FUNCTION__)
        //通过cell找到对应的indexPath
        if let index = collectionView?.indexPathForCell(cell){
            // 在数组中 删除对应的indexPath.item角标下的元素
       imageList.removeAtIndex(index.item)
            //刷新
            collectionView?.reloadData()
        }
        
    }
}

extension PictureSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
//图片选择器的协议方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        print(editingInfo)
        
        //添加到图片数组中
        imageList.append(image)
        //刷新列表
        collectionView?.reloadData()
        //手动dismiss
        dismissViewControllerAnimated(true , completion: nil)
    }
}

//----------------------------------------
//定义协议
@objc protocol PictureSelectorCellDelegate: NSObjectProtocol{
    //定义协议方法
    optional func userWillChoosePicture(cell:PictureSelectorCell)
    //添加参数把自己回调回去
    optional func userWillDeletePicture(cell:PictureSelectorCell)
}


class PictureSelectorCell: UICollectionViewCell{
    
    
    //MARK:定义外部模型属性
    var image:UIImage?{
        didSet{
            //如果设置的图片为空的话就隐藏删除按钮
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    
    //按钮点击事件的响应方法
    @objc private func addBtnDidClick(){
       
        //使用代理调用协议方法
        delegate?.userWillChoosePicture?(self)
        
    }
    @objc private func deleteBtnDidClick(){
        
        delegate?.userWillDeletePicture?(self)
    }
    
    //声明一个弱引用的代理对象
    weak var delegate:PictureSelectorCellDelegate?
    
   
    //MARK:重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:设置页面和布局
    private func setupUI(){
        
        //设置图片的显示样式
        addBtn.imageView?.contentMode = .ScaleAspectFill
        
        
        addSubview(addBtn)
        addSubview(deleteBtn)
        
        //添加约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(self)
        }
        
        //点击事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
    }
    
    //MARK:懒加载所有的子视图
    private lazy var addBtn:UIButton = UIButton(imageName: nil, backgroundImageName: "compose_pic_add")
    private lazy var deleteBtn:UIButton = UIButton(imageName: nil, backgroundImageName: "compose_photo_close")
    
}
